<template>
  <div class="flex items-center justify-center min-h-screen bg-gray-100">
    <div class="w-full max-w-md p-8 space-y-6 bg-white rounded shadow">
      <h2 class="text-2xl font-bold text-center">登录</h2>
      <form @submit.prevent="login" class="space-y-4">
        <input v-model="username" type="text" placeholder="用户名" class="w-full px-4 py-2 border rounded" required />
        <input v-model="password" type="password" placeholder="密码" class="w-full px-4 py-2 border rounded" required />
        <button type="submit" class="w-full py-2 bg-green-500 text-white rounded hover:bg-green-600">
          登录
        </button>
      </form>
      <p class="text-sm text-center text-red-500">{{ error }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'

const username = ref('')
const password = ref('')
const error = ref('')

const login = async () => {
  try {
    const res = await axios.post('/api/login', {
      username: username.value,
      password: password.value
    })
    localStorage.setItem('token', res.data.access_token)
    window.location.href = '/api/protected'
  } catch (err) {
    error.value = err.response?.data?.detail || '登录失败'
  }
}
</script>
